package cn.iocoder.yudao.module.book.controller.admin.users;

import cn.iocoder.yudao.module.book.controller.admin.books.vo.BooksSaveReqVO;
import cn.iocoder.yudao.module.book.controller.admin.users.vo.userDTOPageReqVO;
import cn.iocoder.yudao.module.book.controller.admin.users.vo.userDTORespVO;
import cn.iocoder.yudao.module.book.controller.admin.users.vo.userDTOSaveReqVO;
import cn.iocoder.yudao.module.book.dal.dataobject.books.BooksDO;
import cn.iocoder.yudao.module.book.util.MinioUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.book.dal.dataobject.users.userDTODO;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/book/user-DTO")
@Validated
public class userDTOController {

    @Resource
    private MinioUtils minioUtils;

    @Resource
    private userDTOService userDTOService;

    @PostMapping("/create")
    @Operation(summary = "创建用户")
    @PreAuthorize("@ss.hasPermission('book:user-DTO:create')")
    public CommonResult<Long> createuserDTO(@Valid @RequestBody userDTOSaveReqVO createReqVO) {
        return success(userDTOService.createuserDTO(createReqVO));
    }

    @PostMapping("/create-with-image")
    @Operation(summary = "创建中英文绘本（带图片）")
    @PreAuthorize("@ss.hasPermission('book:s:create')")
    public CommonResult<Long> createUserWithImage(
            @Valid userDTOSaveReqVO saveReqVO,
            @Parameter(description = "绘本图片", required = true)
            @RequestParam("imageFile") MultipartFile imageFile) {
        try {
            // 上传图片到MinIO
            List<String> fileNames = minioUtils.upload(new MultipartFile[]{imageFile});
            if (fileNames.isEmpty()) {
                return CommonResult.error(500,"图片上传失败");
            }

            // 构建BooksDO对象
            userDTODO user = new userDTODO();
            // 设置书籍基本信息
            user.setNickname(saveReqVO.getNickname());

            // 设置图片URL（需要根据MinIO访问策略构建完整URL）
            String imageUrl = buildImageUrl(fileNames.get(0));
            user.setAvatarUrl(imageUrl);

            // 调用原有的创建方法
            return CommonResult.success(userDTOService.createuserDTO(saveReqVO));
        } catch (Exception e) {
            return CommonResult.error(500,"图片上传失败");
        }
    }

    private String buildImageUrl(String fileName) {
        // 根据MinIO配置构建完整的图片访问URL
        // 示例: http://minio-endpoint/bucket-name/filename
        return "http://192.168.110.128:9000/abc/" + fileName;
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户")
    @PreAuthorize("@ss.hasPermission('book:user-DTO:update')")
    public CommonResult<Boolean> updateuserDTO(@Valid @RequestBody userDTOSaveReqVO updateReqVO) {
        userDTOService.updateuserDTO(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('book:user-DTO:delete')")
    public CommonResult<Boolean> deleteuserDTO(@RequestParam("id") Integer id) {
        userDTOService.deleteuserDTO(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('book:user-DTO:query')")
    public CommonResult<userDTORespVO> getuserDTO(@RequestParam("id") Long id) {
        userDTODO userDTO = userDTOService.getuserDTO(id);
        return success(BeanUtils.toBean(userDTO, userDTORespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页")
    @PreAuthorize("@ss.hasPermission('book:user-DTO:query')")
    public CommonResult<PageResult<userDTORespVO>> getuserDTOPage(@Valid userDTOPageReqVO pageReqVO) {
        PageResult<userDTODO> pageResult = userDTOService.getuserDTOPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, userDTORespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户 Excel")
    @PreAuthorize("@ss.hasPermission('book:user-DTO:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportuserDTOExcel(@Valid userDTOPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<userDTODO> list = userDTOService.getuserDTOPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户.xls", "数据", userDTORespVO.class,
                        BeanUtils.toBean(list, userDTORespVO.class));
    }

}